<template>
    <div class="newDepartment">
        <div class="crumbs">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item>
                    <i class="el-icon-folder" style="margin-right:10px"></i>模板管理
                </el-breadcrumb-item>
                <el-breadcrumb-item>添加模板</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <div class="stateTime mr20">
                    <el-select
                        class="newFormInput"
                        v-model="query.startdate"
                        placeholder="请选择开始上报时间"
                    >
                        <el-option v-for="day in 31" :key="day" :label="`每月 ${day} 日`" :value="day"></el-option>
                    </el-select>
                </div>
                <div class="stateTime mr20">
                    <el-select class="newFormInput" v-model="query.enddate" placeholder="请选择结束上报时间">
                        <el-option v-for="num in 31" :key="num" :label="`每月 ${num} 日`" :value="num"></el-option>
                    </el-select>
                </div>
                <el-button
                    type="primary"
                    class="titleBtn confirm"
                    style="width:90px"
                    @click="confirmadd"
                >确定</el-button>
            </div>
            <div class="tableBox">
                <el-table
                    :data="stu"
                    style="width: 100%;margin-bottom: 20px;"
                    row-key="id"
                    border
                    default-expand-all
                    :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                >
                    <el-table-column prop="name" align="center" label="分类名称">
                        <template slot-scope="scope">
                            <div class="rowFirst">
                                <span v-if="scope.row.status === 2">{{scope.row.name}}</span>
                                <el-input
                                    v-else
                                    :disabled="scope.row.status === 2"
                                    maxlength="10"
                                    v-model="scope.row.name"
                                    placeholder="请输入分类名称"
                                ></el-input>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="budgetScale" align="center" label="默认预算比例">
                        <template slot-scope="scope">
                            <el-input
                                :disabled="scope.row.status === 2"
                                v-model.number="scope.row.budgetScale"
                                @blur="isNumber(scope.row)"
                                placeholder="请输入默认预算比例"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="recorderRoleId" align="center" label="记录员角色">
                        <template slot-scope="scope">
                            <el-select
                                v-model="scope.row.recorderRoleId"
                                placeholder="请选择"
                                :disabled="scope.row.status === 2 || scope.row.isCheckRecord"
                                @change="jlyChange(scope.row.recorderRoleId,scope.row.id,1)"
                                class="td-input"
                            >
                                <el-option
                                    v-for="item in registrar"
                                    :key="item.id"
                                    :label="item.roleName"
                                    :value="item.id"
                                ></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="auditorRoleId" align="center" label="审核员角色">
                        <template slot-scope="scope">
                            <el-select
                                :disabled="scope.row.status === 2 || scope.row.isCheckAuditor"
                                @change="jlyChange(scope.row.auditorRoleId,scope.row.id,2)"
                                v-model="scope.row.auditorRoleId"
                                placeholder="请选择"
                                class="td-input"
                            >
                                <el-option
                                    v-for="item in auditor"
                                    :key="item.id"
                                    :label="item.roleName"
                                    :value="item.id"
                                ></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="action" align="center" label="操作">
                        <template slot-scope="scope">
                            <el-button
                                type="primary"
                                v-if="scope.row.status == 1"
                                @click="scope.row.status = 2"
                            >保存</el-button>
                            <el-button
                                type="primary"
                                v-if="scope.row.status == 2"
                                @click="scope.row.status = 1"
                            >编辑</el-button>
                            <el-button
                                type="success"
                                v-if="scope.row.level!==3"
                                @click="addRow(scope.row)"
                            >添加</el-button>
                            <el-button type="danger" @click="delRow(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="add_icon">
                <img @click="insert" src="@/assets/img/icon_add.png" />
            </div>
        </div>

        <!-- 新增弹出框 -->
        <el-dialog title="新增" :visible.sync="nameVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="模板名称">
                    <el-input v-model.trim="form.modelName"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="nameVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { commongetRoleList, modeladd } from '../../api/index.js';
export default {
    name: 'basetable',
    data() {
        return {
            query: {
                userid: localStorage.getItem('userid'),
                page: 1,
                pageSize: 10
            },
            nameVisible: false,
            registrar: [], //记录员下拉列表
            auditor: [], //审核员下拉列表
            user: {
                name: '',
                budgetScale: 0,
                recorderRoleId: '',
                auditorRoleId: '',
                level: 1,
                status: 1,
                isCheckRecord: false, // 角色是否可以选择
                isCheckAuditor: false, // 审核员是否可选
                children: []
            },
            stu: [
                {
                    id: '1',
                    name: '',
                    level: 1,
                    status: 1, // 1新增可编辑状态2编辑完成不可修改
                    budgetScale: 100,
                    recorderRoleId: '',
                    auditorRoleId: '',
                    children: []
                }
            ],
            form: {
                modelName: ''
            },
            pageSize: 10,
            pageTotal: 0
        };
    },
    created() {
        this.getroule(1);
        this.getroule(2);
    },
    methods: {
        // 获取角色下拉列表
        getroule(type) {
            commongetRoleList({ type: type }).then((res) => {
                if (res.code == 200) {
                    if (type == 1) {
                        this.registrar = res.result || [];
                    } else if (type == 2) {
                        this.auditor = res.result || [];
                    }
                }
            });
        },
        // 判断是不是数字
        isNumber(item) {
            console.log(typeof item.budgetScale);
            item.budgetScale = typeof item.budgetScale === 'number' ? item.budgetScale : null;
        },
        // 点击添加
        insert() {
            let data = JSON.parse(JSON.stringify(this.user));
            data.id = toString(this.stu.length + 1);
            this.stu.push(data);
        },
        // 行点击新增
        addRow(row) {
            let data = JSON.parse(JSON.stringify(this.user));
            data.id = `${row.id}${row.children.length}`;
            data.level = row.level === 1 ? 2 : 3;
            if (row.recorderRoleId) {
                data.recorderRoleId = row.recorderRoleId
                data.isCheckRecord = true
            }
            if (row.auditorRoleId) {
                data.auditorRoleId = row.auditorRoleId;
                data.isCheckAuditor = true
            }
            row.children.push(data);
        },
        // 行点击删除
        delRow(row) {
            let delId = row.id;
            let indexArry = this.findIndex(delId);
            if (indexArry.length == 1) this.stu.splice(indexArry[0], 1);
            if (indexArry.length == 2) this.stu[indexArry[0]].children.splice(indexArry[1], 1);
            if (indexArry.length == 3) this.stu[indexArry[0]].children[indexArry[2]].children.splice(indexArry[2], 1);
        },
        // 返回index
        findIndex(id) {
            let list = this.stu;
            let indexArry = [];
            for (let i = 0; i < list.length; i++) {
                if (list[i].id == id) {
                    indexArry.push(i);
                    break;
                }
                let childOne = list[i].children;
                for (let t = 0; t < childOne.length; t++) {
                    if (childOne[t].id == id) {
                        indexArry.push(i, t);
                        break;
                    }
                    let childTwo = childOne[t].children;
                    for (let f = 0; f < childTwo.length; f++) {
                        if (childTwo[f].id === id) {
                            indexArry.push(i, t, f);
                            break;
                        }
                    }
                }
            }
            return indexArry;
        },
        // 记录员角色change事件
        jlyChange(value, id, type) {
            let array = this.findIndex(id);
            let childlist =
                array.length === 1
                    ? (childlist = this.stu[array[0]].children)
                    : array.length === 2
                    ? (childlist = this.stu[array[0]].children[array[1]].children)
                    : [];
            let change = function (list) {
                if (list.length > 0) {
                    list.forEach((item) => {
                        item[`${type == 1 ? 'recorderRoleId' : 'auditorRoleId'}`] = value;
                        if (item.children.length > 0) {
                            change(item.children);
                        }
                    });
                }
            };
            change(childlist);
        },
        // 确定新增
        confirmadd() {
            //开始上报时间
            if (!this.query.startdate) {
                this.$message.error('开始上报时间不能为空');
                return;
            }
            //结束上报时间
            if (!this.query.enddate) {
                this.$message.error('结束上报时间不能为空');
                return;
            }
            if (this.stu.length<1) {
                this.$message.error('请先添加分类');
                return;
            }
            this.nameVisible = true;
        },
        saveEdit() {
            let that = this
            //上报时间
            if (!this.form.modelName) {
                this.$message.error('模板名称不能为空');
                return;
            }
            // 重构数据
            let dataArray = this.stu.map((item) => {
                let array = [];
                if (item.children.length > 0) {
                    array = item.children.map((childOne) => {
                        let array1 = [];
                        if (childOne.children.length > 0) {
                            array1 = childOne.children.map((childTwo) => {
                                return {
                                    auditorRoleId: childTwo.auditorRoleId,
                                    recorderRoleId: childTwo.recorderRoleId,
                                    budgetScale: childTwo.budgetScale,
                                    threeLevelName: childTwo.name
                                };
                            });
                        }
                        return {
                            auditorRoleId: childOne.auditorRoleId,
                            twoLevelName: childOne.name,
                            recorderRoleId: childOne.recorderRoleId,
                            budgetScale: childOne.budgetScale,
                            array: array1
                        };
                    });
                }
                return {
                    oneLevelName: item.name,
                    auditorRoleId: item.auditorRoleId,
                    recorderRoleId: item.recorderRoleId,
                    budgetScale: item.budgetScale,
                    array: array
                };
            });
            console.log(dataArray);
            // 前端限制 新增模板时，二级分类下的审核记录员为必选项
            let breaked = false
            for (let i=0;i<dataArray.length;i++) {
                if (dataArray[i].array&&dataArray[i].array.length>0){
                    let arry2 = dataArray[i].array
                    for (let t=0;t<arry2.length;t++) {
                        if (!arry2[t].auditorRoleId) {
                            this.$message.error('请选择二级分类下的审核员');
                            breaked = true
                            break;
                        }
                    }
                }
                if (breaked) {
                    break;
                }
            }
            let form = {
                startTime: this.query.startdate,
                endTime: this.query.enddate,
                modelName: this.form.modelName,
                dataArray: dataArray
            };
            modeladd(form).then((res) => {
                console.log(res);
                if (res.code == 200) {
                    this.$message.success('新增成功');
                    this.$router.push('/template');
                } else this.$message.error(res.message);
            });
        }
    }
};
</script>

<style scoped lang="scss">
.container {
    box-shadow: none;
    margin-top: 0;
}
.newDepartment {
    min-width: 1400px;
    height: 100%;
}
.handle-box {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    overflow: hidden;
    width: 100%;
    // margin-left:1.25rem /* 20/16 */;
    margin-right: 1.25rem /* 20/16 */;
}
.title {
    height: 28px;
    font-size: 20px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: rgba(51, 51, 51, 1);
    margin-right: 80px;
    min-width: 120px;
}
.mr20 {
    font-size: 14px;
    // margin-right: 8px;
    min-width: 223px;
}
.crumbs {
    margin-bottom: 1.875rem /* 30/16 */;
}
.titleBtn {
    width: 90px;
    height: 35px;
    background: #004fab;
    color: #fff;
    border: none;
    font-size: 16px;
    border-radius: 5px;
}
.confirm {
    margin-left: auto;
}
.titleBtn1 {
    width: 90px;
    height: 35px;
    background: rgba(0, 79, 171, 0.2);
    color: rgba(0, 79, 171, 1);
    border: none;
    font-size: 16px;
    border-radius: 5px;
}
.handle-box .name {
    margin-right: 10px;
}
.mr20 {
    margin-right: 30px;
    min-width: 240px;
}
.handle-select {
    width: 160px;
}
.searchBox {
    min-width: 240px;
    margin-left: auto;
}
.add_icon {
    width: 100%;
    margin-top: 1.875rem /* 30/16 */;
    text-align: center;
}
.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.title {
    float: left;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.newForm {
    .el-form-item {
        border-bottom: 1px solid #d8d8d8;
        margin-bottom: 0;
    }
    .newFormInput/deep/.el-input__inner {
        border: none;
        width: 450px;
        height: 62px;
        line-height: 62px;
    }
    /deep/.el-form-item__label {
        font-size: 16px;
        padding: 0;
        line-height: 62px;
    }
}
.newDepartment/deep/.el-dialog__body {
    max-height: 400px;
    margin-top: 16px;
    // padding-top:155px!important;
    overflow-y: scroll;
    position: relative;
}
.tableBtnBox {
    text-align: center;
    .btn1 {
        width: 90px;
        height: 35px;
        background: rgba(0, 79, 171, 0.2);
        border-radius: 5px;
        border: none;
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(0, 79, 171, 1);
        margin-right: 56px;
    }
    .btn2 {
        width: 90px;
        height: 35px;
        background: rgba(0, 79, 171, 1);
        border-radius: 5px;
        border: none;
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);
    }
    /deep/.el-input.is-disabled > .el-input__inner {
        background: #fff !important;
    }
}
.newObjectConfirm {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(255, 255, 255, 1);
    line-height: 28px;
    background: rgba(0, 79, 171, 1) !important;
}
.newObjectCancel {
    width: 90px !important;
    height: 35px;
    background: rgba(255, 255, 255, 0.2) !important;
    border-radius: 5px;
}
.newForm/deep/.el-input__inner {
    font-size: 16px;
}
.el-input--suffix .el-input__inner {
    padding-right: 0;
}
/* 弹出框样式 */
.td-input {
    width: 80%;
    border: none;
    height: 40px;
    text-align: center;
}
.tableTitle {
    background: rgba(184, 216, 255, 0.2);
    border: 1px solid rgba(184, 216, 255, 1);
    margin: 0;
    min-width: 33%;
    height: 40px;
}
.newObjectList >>> .el-dialog__body {
    padding: 0 0px 30px 30px;
}
.tr1 {
    height: 40px;
}
.tr1 input {
    height: 30px;
}
.tr2 {
    height: 40px;
    background: rgba(184, 216, 255, 0.05);
}
.tr2 input {
    background: transparent;
    height: 30px;
}
#table {
    border-collapse: collapse;
}
#table td {
    border: 1px solid rgba(184, 216, 255, 1);
}
/deep/.td-input {
    height: 32px;
}
.rowFirst {
    display: inline-block;
}
</style>
